package com.skyk.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.skyk.pojo.dto.UserAddDTO;
import com.skyk.pojo.dto.UserDTO;
import com.skyk.pojo.dto.UserLoginDTO;
import com.skyk.pojo.entity.User;
import com.skyk.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.skyk.util.Result;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /*
     * Get方式：参数在URL中
     * Post方式：参数在请求体中
     *登录时需要传输用户名和密码等敏感信息，使用POST方法更安全可靠*/
    @PostMapping("/login")
    public String loginController(@RequestBody UserLoginDTO userLoginDTO) {
        String sessionKey = userService.loginService(userLoginDTO);

        if (sessionKey != null) {
            return sessionKey;
        } else {
            return null;
        }
    }


  /*  //新建一个测试session的接口，测试是否前端带过来了sessionKey，并且能获取到当前用户信息
    @GetMapping("/test-session")
    public boolean testSession() {
        User user = UserContext.getUser();
        log.info("用户信息:" + user);
        return true;
    }*/


    /*分页查询：
     * 根据用户名、性别、手机号码进行查询，其中用户名模糊查询
     * 分页查询返回给前端分页信息和查询结果(UserDTO)
     */
    @GetMapping("/page")
    public IPage<UserDTO> getUsersPage(
            @RequestParam(defaultValue = "1") int currentPage,//当前所在页码
            @RequestParam(defaultValue = "10") int pageSize,//一页展示多少条数据
            @RequestParam(required = false) String username,//可选
            @RequestParam(required = false) String gender,
            @RequestParam(required = false) String phoneNumber
    ) {
        // 验证页码和每页数量是否为合理值
        if (currentPage <= 0) {
            currentPage = 1; // 默认第一页
        }
        if (pageSize <= 0 || pageSize > 100) { // 假设最大每页不超过100条
            pageSize = 5; // 默认每页5条
        }
        //封装分页信息（当前页码和每页记录数）
        Page<User> page = new Page<>(currentPage, pageSize);
        //返回对象包含了分页信息和查询结果(UserDTO)
        return userService.getUsersPage(page, username, gender, phoneNumber);
    }


    /*
     *根据id进行逻辑删除
     * */
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Long id) { //@PathVariable用于从URI中提取变量
        userService.logicDeleteUserById(id);
        return Result.success();
    }

    /*
     * 启用或禁用用户
     * */
    @PutMapping("/state/{state}")
    public Result updateOrStop(@RequestParam(required = false) Long id, @PathVariable Boolean state) {
        userService.updateOrStop(state, id);
        return Result.success();
    }

    /*
     * 新增用户
     * */
    @PostMapping("/add")
    public Result addUser(@RequestBody UserAddDTO userAddDTO) {
        return userService.addUser(userAddDTO);
    }

    /*
     * 更新用户信息
     * */
    @PutMapping("/{id}")
    public Result update(@PathVariable Long id, @RequestBody UserAddDTO userAddDTO) {
        return userService.updateUser(id, userAddDTO);
    }

    //按照搜索条件导出，除了密码，全部字段导出
    @GetMapping("/export")
    public void exportUsers(@RequestParam(required = false) String username,
                            @RequestParam(required = false) String gender,
                            @RequestParam(required = false) String phoneNumber,
                            HttpServletResponse response) throws IOException {
        userService.exportUsers(response, username, gender, phoneNumber);
    }

    /**
     * 导出用户
     */
    @GetMapping("/exportUsersV2")
    public void exportUsersV2(@RequestParam(required = false) String username,
                            @RequestParam(required = false) String gender,
                            @RequestParam(required = false) String phoneNumber,
                            HttpServletResponse response) throws IOException {
        userService.exportUsersV2(response, username, gender, phoneNumber);
    }

    /**
     * 导入用户
     */
    @PostMapping("/importUsers")
    public void importUsers(MultipartFile file) throws IOException {
        userService.importUsers(file);
    }
    
}



